package ouc.pkere.utils.generator.codegen;

import ouc.pkere.utils.generator.utils.CommonUtils;

import java.io.File;

/**
 * RestController代码生成器
 *
 * @author Wang xiaodong
 * 2018-06-11 22:37
 *
 */
public class RestControllerJavaCodeGenerator {

    private String packageName;
    private String packagePath;
    private String moduleName;

    public RestControllerJavaCodeGenerator() {
    }

    public RestControllerJavaCodeGenerator(String pkgName,
                                           String pkgPath,
                                           String moduleName) {
        super();
        this.packageName = pkgName;
        this.packagePath = pkgPath;
        this.moduleName = moduleName;
    }

    public void generate() {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageName + ".service;\r\n\r\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
        sb.append("import org.springframework.data.domain.Page;\r\n");
        sb.append("import org.springframework.data.domain.PageRequest;\r\n");
        sb.append("import org.springframework.data.domain.Pageable;\r\n");
        sb.append("import org.springframework.data.domain.Sort;\r\n");
        sb.append("import org.springframework.stereotype.Service;\r\n\r\n");

        // 生成导入本模块Entity的字符串
        sb.append("import " + this.packageName + ".entity." + this.moduleName + "Entity;\r\n");

        // 生成导入本模块Repository的字符串
        sb.append("import " + this.packageName + ".repository." + this.moduleName + "Repository;\r\n\r\n");

        // 生成@Service注解字符串
        sb.append("@Service\r\n");

        sb.append("public class " + this.moduleName + "Service {\r\n\r\n");

        // 生成@Autowired注解字符串
        sb.append("\t@Autowired\r\n");

        sb.append("\tprivate " + this.moduleName + "Repository theRepository;\r\n\r\n");

        sb.append("\tpublic Page<" + this.moduleName + "Entity> " + "listAllByPages(Integer start, Integer length) {\r\n");

        sb.append("\t\tInteger pageNo = start / length;\r\n");
        sb.append("\t\tPageable pageable = new PageRequest(pageNo, length, Sort.Direction.ASC, \"id\");\r\n");
        sb.append("\t\tPage<" + this.moduleName + "Entity> pages = theRepository.findAll(pageable);\r\n");
        sb.append("\t\treturn pages;\r\n\r\n");
        sb.append("\t}\r\n");
        sb.append("}\r\n");


        // Service的完整生成路径包含service子目录
        String serviceFullPath = this.packagePath + File.separator + "service";

        File serviceFullPathFp = new File(serviceFullPath);

        if (!serviceFullPathFp.exists()) {
            serviceFullPathFp.mkdir();
        }

        String serviceJavaFilePathName = serviceFullPath + File.separator +
                this.moduleName + "Service" + ".java";

        System.out.println(serviceJavaFilePathName);

        CommonUtils.codeToSrcFile(serviceJavaFilePathName, sb.toString());
    }


    public static void main(String[] args) {

    }
}